const mongoose = require('../util/db').mongoose
const Schema = mongoose.Schema;
const db = require('../util/db').db
const todoSchema = new Schema({
    content: String,
    pubDate: Date,
    complete: String
})
const Todo = db.model('Todo', todoSchema)

async function getController(req, res, next) {
    try {
        let todoList = await Todo.find({}).exec()
        // console.log(todoList);
        res.render('index', { title: 'todo app', todoList: todoList });
    } catch (error) {
        throw error
    }
}
async function getByIdController(req, res, next) {
    try {
        let _id = req.params.id
        console.log(_id);
        let todo = await Todo.findById(_id).exec()
        console.log(todo);
        res.render('detail', { title: 'todo detail', todo: todo })
    } catch (error) {

    }
}
async function postController(req, res, next) {
    try {
        let content = req.body.content
        content.pubDate = new Date()
        await Todo({
            content: content,
            pubDate: new Date(),
            complete: '0'
        }).save()
        // console.log(todoList);
        res.send("新增成功")
    } catch (error) {

    }
}

async function putController(req, res, next) {
    try {
        let _id = req.params.id
        console.log(_id);

        console.log(req.body);

        let complete = req.body.complete;
        // console.log(complete);

        await Todo.findByIdAndUpdate(_id, { $set: { complete: complete } }).exec()
        console.log("finished!");
        res.send("更新成功")
    } catch (error) {

    }
}

async function deleteController(req, res, next) {
    let _id = req.params.id
    await Todo.findByIdAndRemove(_id).exec()
    res.send("删除成功")
}


module.exports = {
    getController,
    getByIdController,
    postController,
    putController,
    deleteController
}
// const Cat = mongoose.model('Cat', { name: String });